package com.jader.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import com.google.gson.Gson;
import com.jader.beans.User;
import com.jader.util.CommonUtils;
import com.jader.util.JaderApplication;
import com.jader.util.MD5Tool;
import com.jader.util.PreferenceUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

public class RegisterActivity extends Activity {
	Button register_finish, register_sendMsg;
	EditText edit_register_name, edit_register_password,
			edit_register_phoneNum;
	ImageView register_back;
	TextView register_title;
	int i = 30;
	private String phoneNum = "";
	private String url = JaderApplication.getIP() + "/Jader/client";
	String registerName = "";
	String registerPassword = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		initSDK();
		initView();
		viewListener();
	}

	/** 验证手机号是否已注册 */

	private void viewListener() {
		registerName = edit_register_name.getText().toString().trim();
		registerPassword = edit_register_password.getText().toString().trim();
		edit_register_phoneNum.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) { // TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) { // TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				phoneNum = edit_register_phoneNum.getText().toString().trim();
				checkPhoneNum();
			}
		});

		edit_register_name
				.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						if (TextUtils.isEmpty(registerName)) {
							JaderApplication.show(getBaseContext(), "请输入用户名");
						}
					}
				});
		edit_register_password
				.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						if (TextUtils.isEmpty(registerPassword)) {
							JaderApplication.show(getBaseContext(), "请输入密码");
						}

					}
				});
		edit_register_phoneNum
				.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						if (TextUtils.isEmpty(phoneNum)) {
							JaderApplication.show(getBaseContext(), "请输入手机号");
						}

					}
				});

	}

	/**
	 * 初始化视图
	 */
	private void initView() {
		register_sendMsg = (Button) findViewById(R.id.btn_register_send_msg);
		register_finish = (Button) findViewById(R.id.btn_register_finish);
		edit_register_name = (EditText) findViewById(R.id.edit_register_name);
		edit_register_password = (EditText) findViewById(R.id.edit_register_password);
		edit_register_phoneNum = (EditText) findViewById(R.id.edit_register_phoneNum);
		register_back = (ImageView) findViewById(R.id.top_actionbar_back);
		register_title = (TextView) findViewById(R.id.top_actiobar_text);
		register_title.setText("注册");
	}

	/**
	 * 初始化短信APISDK
	 */
	private void initSDK() {
		// 启动短信验证sdk
		SMSSDK.initSDK(RegisterActivity.this, JaderApplication.getAPPKEY(),
				JaderApplication.getAPPSECRRET());
		EventHandler eventHandler = new EventHandler() {
			@Override
			public void afterEvent(int event, int result, Object data) {
				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				handler.sendMessage(msg);
			}
		};
		// 注册回调监听接口
		SMSSDK.registerEventHandler(eventHandler);
	}

	/** 发送短信单击事件 */
	public void sendMsg(View view) {
		phoneNum = edit_register_phoneNum.getText().toString().trim();
		// 1. 通过规则判断手机号
		if (!CommonUtils.judgePhoneNums(phoneNum)) {
			return;
		}
		// 2. 通过sdk发送短信验证
		SMSSDK.getVerificationCode("86", phoneNum);
		// 3. 把按钮变成不可点击，并且显示倒计时（正在获取）
		register_sendMsg.setClickable(false);
		register_sendMsg.setText("重新发送(" + i + ")");
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (; i > 0; i--) {
					handler.sendEmptyMessage(-9);
					if (i <= 0) {
						break;
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				handler.sendEmptyMessage(-8);
			}
		}).start();
	}

	/** 注册完成单击事件 */
	public void registerFinish(View view) {

		String register_name = edit_register_name.getText().toString().trim();
		String register_enpassword = MD5Tool.MD5(edit_register_password
				.getText().toString().trim());
		RequestParams params = new RequestParams();
		params.addBodyParameter("type", "" + JaderApplication.INSERT_USER);
		params.addBodyParameter("username", register_name);
		params.addBodyParameter("password", register_enpassword);
		params.addBodyParameter("phoneNum", phoneNum);
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						JaderApplication.show(getBaseContext(), arg1.toString());

					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						String result = info.result;
						if ("fail".equals(result)) {
							JaderApplication.show(getBaseContext(), "出错了,再试试吧");
						} else {
							Gson gson = new Gson();
							User user = gson.fromJson(result, User.class);
							String userid = "" + user.getUserid();
							String username = user.getUsername();
							String password = user.getPassword();
							String phone = user.getPhone();
							String picture = user.getPicture();
							String gender = user.getGender();
							double money = user.getMoney();
							PreferenceUtil.getInstance(getApplicationContext())
									.setSharePassWord(password);
							PreferenceUtil.getInstance(getApplicationContext())
									.setShareUserGender(gender);
							PreferenceUtil.getInstance(getApplicationContext())
									.setShareUserId(userid);
							PreferenceUtil.getInstance(getApplicationContext())
									.setShareUserName(username);
							PreferenceUtil.getInstance(getApplicationContext())
									.setShareUserPhone(phone);
							PreferenceUtil.getInstance(getApplicationContext())
									.setShareUserPic(picture);
							PreferenceUtil.getInstance(getApplicationContext())
									.setShareUserMoney(money);
							JaderApplication.show(getBaseContext(), "开启寻宝之旅~");
							startActivity(new Intent(getBaseContext(),
									UserInfoActivity.class));

						}
					}
				});
	}

	/**
	 * 处理短信注册的handle
	 */
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == -9) {
				register_sendMsg.setText("重新发送(" + i + ")");
			} else if (msg.what == -8) {
				register_sendMsg.setText("获取验证码");
				register_sendMsg.setClickable(true);
			} else {
				int event = msg.arg1;
				int result = msg.arg2;
				Object data = msg.obj;
				Log.e("event", "event=" + event);
				if (result == SMSSDK.RESULT_COMPLETE) {
					// 短信注册成功后，返回MainActivity,然后提示
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
						// 提交验证码成功
						JaderApplication.show(getBaseContext(), "提交验证码成功");
					} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
						JaderApplication.show(getBaseContext(), "验证码在路上了,不要着急");
					} else {
						((Throwable) data).printStackTrace();
					}
				}
			}
		}
	};

	private void checkPhoneNum() {
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("type", "" + JaderApplication.CHECK_PHONE);
		params.addBodyParameter("phoneNum", phoneNum);
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@SuppressLint("NewApi")
					@Override
					public void onSuccess(ResponseInfo<String> info) {
						String result = info.result;
						if ("have".equals(result)) {
							JaderApplication.show(getBaseContext(), "已经被注册了");
							register_sendMsg.setBackgroundColor(Color.GRAY);
							register_sendMsg.setClickable(false);
						} else {
							register_sendMsg.setBackground(getResources()
									.getDrawable(R.drawable.jadercolor));

							register_sendMsg.setClickable(true);
						}
					}
				});
	}

	@Override
	protected void onDestroy() {
		SMSSDK.unregisterAllEventHandler();
		finish();
		super.onDestroy();
	}
}
